package com.ruoyi.dataBase.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.dataBase.domain.IndustrialTransportPlan;
import com.ruoyi.dataBase.mapper.IndustrialTransportPlanMapper;
import com.ruoyi.dataStatistics.domain.industrialProjectAnalysisVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.dataBase.domain.bo.IndustrialTransportProjectBo;
import com.ruoyi.dataBase.domain.vo.IndustrialTransportProjectVo;
import com.ruoyi.dataBase.domain.IndustrialTransportProject;
import com.ruoyi.dataBase.mapper.IndustrialTransportProjectMapper;
import com.ruoyi.dataBase.service.IIndustrialTransportProjectService;

import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 交通物流项目Service业务层处理
 *
 * @author yangzhen
 * @date 2025-11-10
 */
@RequiredArgsConstructor
@Service
public class IndustrialTransportProjectServiceImpl implements IIndustrialTransportProjectService {

    private final IndustrialTransportProjectMapper baseMapper;

    private final IndustrialTransportPlanMapper industrialTransportPlanMapper;

    /**
     * 查询交通物流项目
     */
    @Override
    public IndustrialTransportProjectVo queryById(String id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询交通物流项目列表
     */
    @Override
    public TableDataInfo<IndustrialTransportProjectVo> queryPageList(IndustrialTransportProjectBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<IndustrialTransportProject> lqw = buildQueryWrapper(bo);
        Page<IndustrialTransportProjectVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        if (CollectionUtils.isNotEmpty(result.getRecords())) {
            List<IndustrialTransportProjectVo> records = result.getRecords();
            List<String> planIdList = result.getRecords().stream().map(IndustrialTransportProjectVo::getPlanId).collect(Collectors.toList());
            List<IndustrialTransportPlan> industrialTransportPlans = industrialTransportPlanMapper.selectBatchIds(planIdList);
            if (CollectionUtils.isNotEmpty(industrialTransportPlans)) {
                Map<String, IndustrialTransportPlan> map = industrialTransportPlans.stream().distinct().collect(Collectors.toMap(IndustrialTransportPlan::getId, Function.identity()));
                records.forEach(industrialTransportProjectVo -> {
                    if (map.get(industrialTransportProjectVo.getPlanId()) != null) {
                        industrialTransportProjectVo.setPlanName(map.get(industrialTransportProjectVo.getPlanId()).getPlanName());
                    }
                });
                result.setRecords(records);
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询交通物流项目列表
     */
    @Override
    public List<IndustrialTransportProjectVo> queryList(IndustrialTransportProjectBo bo) {
        LambdaQueryWrapper<IndustrialTransportProject> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<IndustrialTransportProject> buildQueryWrapper(IndustrialTransportProjectBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<IndustrialTransportProject> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getProjectName()), IndustrialTransportProject::getProjectName, bo.getProjectName());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectType()), IndustrialTransportProject::getProjectType, bo.getProjectType());
        lqw.eq(StringUtils.isNotBlank(bo.getProjectCategory()), IndustrialTransportProject::getProjectCategory, bo.getProjectCategory());
        lqw.eq(StringUtils.isNotBlank(bo.getPlanId()), IndustrialTransportProject::getPlanId, bo.getPlanId());
        lqw.eq(bo.getStartDate() != null, IndustrialTransportProject::getStartDate, bo.getStartDate());
        lqw.eq(StringUtils.isNotBlank(bo.getBuildCompany()), IndustrialTransportProject::getBuildCompany, bo.getBuildCompany());
        lqw.eq(StringUtils.isNotBlank(bo.getMainEntity()), IndustrialTransportProject::getMainEntity, bo.getMainEntity());
        lqw.eq(StringUtils.isNotBlank(bo.getBuildStatus()), IndustrialTransportProject::getBuildStatus, bo.getBuildStatus());
        lqw.eq(bo.getEndDate() != null, IndustrialTransportProject::getEndDate, bo.getEndDate());
        lqw.eq(bo.getPlanStartDate() != null, IndustrialTransportProject::getPlanStartDate, bo.getPlanStartDate());
        lqw.eq(bo.getPlanEndDate() != null, IndustrialTransportProject::getPlanEndDate, bo.getPlanEndDate());
        lqw.eq(bo.getTotalInvest() != null, IndustrialTransportProject::getTotalInvest, bo.getTotalInvest());
        lqw.eq(bo.getCompleteInvest() != null, IndustrialTransportProject::getCompleteInvest, bo.getCompleteInvest());
        lqw.eq(bo.getDataStatus() != null, IndustrialTransportProject::getDataStatus, bo.getDataStatus());


        lqw.like(StringUtils.isNotBlank(bo.getCreateBy()), IndustrialTransportProject::getCreateBy, bo.getCreateBy());
        lqw.like(StringUtils.isNotBlank(bo.getUpdateBy()), IndustrialTransportProject::getUpdateBy, bo.getUpdateBy());
        lqw.between(params.get("beginCreateTime") != null && params.get("endCreateTime") != null,
            IndustrialTransportProject::getCreateTime, params.get("beginCreateTime"), params.get("endCreateTime"));
        lqw.between(params.get("beginUpdateTime") != null && params.get("endUpdateTime") != null,
            IndustrialTransportProject::getCreateTime, params.get("beginUpdateTime"), params.get("endUpdateTime"));

        return lqw;
    }

    /**
     * 新增交通物流项目
     */
    @Override
    public Boolean insertByBo(IndustrialTransportProjectBo bo) {
        IndustrialTransportProject add = BeanUtil.toBean(bo, IndustrialTransportProject.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改交通物流项目
     */
    @Override
    public Boolean updateByBo(IndustrialTransportProjectBo bo) {
        IndustrialTransportProject update = BeanUtil.toBean(bo, IndustrialTransportProject.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(IndustrialTransportProject entity) {
        //TODO 做一些数据校验,如唯一约束
        if (entity == null || StringUtils.isBlank(entity.getProjectName())) {
            throw new IllegalArgumentException("项目名称不能为空");
        }

        LambdaQueryWrapper<IndustrialTransportProject> queryWrapper =
            new LambdaQueryWrapper<IndustrialTransportProject>()
                .eq(IndustrialTransportProject::getProjectName, entity.getProjectName());

        // 如果是更新操作，排除自身
        if (entity.getId() != null) {
            queryWrapper.ne(IndustrialTransportProject::getId, entity.getId());
        }

        long count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("项目名称已存在");
        }
    }

    /**
     * 批量删除交通物流项目
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public industrialProjectAnalysisVo industrialStationAnalysis() {

        // 1. 查询所有项目（你也可以加条件，如只查有效项目）
        List<IndustrialTransportProject> list = baseMapper.selectList(null);

        // 2. 初始化 Vo
        industrialProjectAnalysisVo vo = new industrialProjectAnalysisVo();

        // 避免 null
        if (CollectionUtils.isEmpty(list)) {
            return vo;
        }

        // 3. 遍历统计
        for (IndustrialTransportProject project : list) {

            String type = project.getProjectType();       // "1"-交通, "2"-物流
            String status = project.getBuildStatus();     // "1规划 / 1待建 / 1在建 / 1已建" ← 你这里是否真实都为 "1"?（可再确认）

            // ========== 交通项目统计 ==========
            if ("1".equals(type)) {

                switch (status) {
                    case "1":  // 规划
                        vo.setTransportProjectPlanned(vo.getTransportProjectPlanned() == null ? 1 :
                            vo.getTransportProjectPlanned() + 1);
                        break;
                    case "2":  // 待建
                        vo.setTransportProjectPending(vo.getTransportProjectPending() == null ? 1 :
                            vo.getTransportProjectPending() + 1);
                        break;
                    case "3":  // 在建
                        vo.setTransportProjectUnderConstruction(vo.getTransportProjectUnderConstruction() == null ? 1 :
                            vo.getTransportProjectUnderConstruction() + 1);
                        break;
                    case "4":  // 已建
                        vo.setTransportProjectCompleted(vo.getTransportProjectCompleted() == null ? 1 :
                            vo.getTransportProjectCompleted() + 1);
                        break;
                }

            }

            // ========== 物流项目统计 ==========
            if ("2".equals(type)) {

                switch (status) {
                    case "1":  // 规划
                        vo.setLogisticsProjectPlanned(vo.getLogisticsProjectPlanned() == null ? 1 :
                            vo.getLogisticsProjectPlanned() + 1);
                        break;
                    case "2":  // 待建
                        vo.setLogisticsProjectPending(vo.getLogisticsProjectPending() == null ? 1 :
                            vo.getLogisticsProjectPending() + 1);
                        break;
                    case "3":  // 在建
                        vo.setLogisticsProjectUnderConstruction(vo.getLogisticsProjectUnderConstruction() == null ? 1 :
                            vo.getLogisticsProjectUnderConstruction() + 1);
                        break;
                    case "4":  // 已建
                        vo.setLogisticsProjectCompleted(vo.getLogisticsProjectCompleted() == null ? 1 :
                            vo.getLogisticsProjectCompleted() + 1);
                        break;
                }

            }
        }

        return vo;
    }

}
